/* 引入express框架 */
const express = require('express');
const bodyParser = require('body-parser');//解析参数
const cors = require('cors');
const mysql = require('mysql');
const app = express();
const router = express.Router();
// 数据库配置
const option = {
    host:'122.51.134.14',
    user:'api_nodejs',
    password:'ic3Yaa7czTkENjtH',
    port:'3306',
    database:'api_nodejs',
    connectTimeout:5000,//链接超时
    multipleStatements:false//是否允许一个query中包含多条sql语句
}

app.use(cors());//解决跨越
app.use(bodyParser.json());//json请求
app.use(bodyParser.urlencoded({extended:false}));//表单请求

let pool;
repool();

// 封装
function Myquery(sql,callback){  
  	pool.getConnection(function(err,connection){  
	    connection.query(sql,function(err,results){  
	      	callback(err, results) // 结果回调
	    	connection.release() // 释放连接资源 | 跟 connection.destroy() 不同，它是销毁
     	})
    }) 
}

function Result({code=1,msg='',data=null}) {
    this.code = code;
    this.msg = msg;
    this.data = data;
}

function repool() {
	pool = mysql.createPool({
		...option,
		waitForConnections:true,//当无连接池可用时，等待（true）还是抛错（false）
		connectionLimit:100,//连接数限制
		queueLimit:0//最大连接等待数（0为不限制）
	});//创立连接池
	pool.on('error',err=>err.code==='PROTOCOL_CONNECTION_LOST' && setTimeout(repool,2000))
}

module.exports = {
	mysql,
	pool,
	Result,
	Myquery,
	router,
	app
}